package com.lebang.service.earn;

import com.lebang.component.RedisClient;
import com.lebang.domain.AppRousePlanDetail;
import com.lebang.example.AppRousePlanDetailExample;
import com.lebang.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * 用户签到数据更改
 *
 * @Author hwq
 * @Date 2020-03-25
 */
@Service
public class AppRousePlanDetailService extends BaseService<AppRousePlanDetail, Integer, AppRousePlanDetailExample> {
    @Autowired
    private RedisClient redisClient;
    private static final String REDIS_KEY = "AppRousePlan:";
    private static final String KEY_MAX_COUNT = "KEY_MAX_COUNT";
    private static final String MEMBER_APPROUSEPLAN_COUNT = "MEMBER_APPROUSEPLAN_COUNT";

    public void initData(String planKey) {

        AppRousePlanDetailExample example = new AppRousePlanDetailExample();
        example.createCriteria().andPlanKeyEqualTo(planKey);
        List<AppRousePlanDetail> list = this.selectByExample(example);
        redisClient.del(REDIS_KEY + planKey);
        list.forEach(s -> {
            redisClient.hset(REDIS_KEY + planKey, s.getCount().toString(), s.getSdkKey());
        });
        redisClient.hset(KEY_MAX_COUNT, planKey, String.valueOf(list.size()));
    }

    /**
     * 根据次数获取轮播
     *
     * @param planKey
     * @return
     */
    public String getKeyByCount(String planKey, String memberId, List<String> filterSdkKey) {
        //取该计划的 轮播最大值
        Optional<String> max = redisClient.Optionalhget(KEY_MAX_COUNT, planKey);
        Integer maxCount = max.map(Integer::parseInt).orElse(3);
        //取该用户轮播到几了 如果到最大了 就从0开始
        Long memberCount = redisClient.hincrby(MEMBER_APPROUSEPLAN_COUNT, memberId, 1L);
        if (memberCount >= maxCount) {
            redisClient.hset(MEMBER_APPROUSEPLAN_COUNT, memberId, "0");
        }
        //取本次轮播的key
        boolean check = true;
        Optional<String> str = Optional.empty();
        int c = 1;
        int count=0;
        while (check || c == maxCount) {
            if(count>maxCount){
                return "NULL";
            }
            str = redisClient.Optionalhget(REDIS_KEY + planKey, String.valueOf(memberCount));
            if (!str.isPresent()) {
                return "NULL";
            } else {
                if (filterSdkKey.contains(str.get())) {
                    memberCount = redisClient.hincrby(MEMBER_APPROUSEPLAN_COUNT, memberId, 1L);
                    if (memberCount >= maxCount) {
                        redisClient.hset(MEMBER_APPROUSEPLAN_COUNT, memberId, "0");
                    }
                } else {
                    check = false;
                }
            }
            c++;
            count++;
        }
        return str.orElse("NULL");
    }


    public boolean check(String s) {
        return redisClient.hexists(KEY_MAX_COUNT, s);
    }
}
